import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';

class SPUtil {
  SPUtil._();

  static SharedPreferences? sharedPreferences;

  static init() async {
    sharedPreferences = await SharedPreferences.getInstance();
  }

  static putString(String key, String? value) {
    sharedPreferences?.setString(key, value ?? "");
  }

  static String getString(String key, String defaultValue) {
    return sharedPreferences?.getString(key) ?? defaultValue;
  }

  static putBool(String key, bool? value) {
    sharedPreferences?.setBool(key, value ?? false);
  }

  static bool getBool(String key, bool defaultValue) {
    return sharedPreferences?.getBool(key) ?? defaultValue;
  }

  static putInt(String key, int? value) {
    sharedPreferences?.setInt(key, value ?? 0);
  }

  static int getInt(String key, int defaultValue) {
    return sharedPreferences?.getInt(key) ?? defaultValue;
  }

  static putDouble(String key, double? value) {
    sharedPreferences?.setDouble(key, value ?? 0);
  }

  static double getDouble(String key, double defaultValue) {
    return sharedPreferences?.getDouble(key) ?? defaultValue;
  }

  static putObject(String key, Map<String, dynamic>? value) {
    var map = value ?? {};
    sharedPreferences?.setString(key, json.encode(map));
  }

  static Map<String, dynamic> getObject(String key) {
    String str = sharedPreferences?.getString(key) ?? json.encode({});
    return json.decode(str) ?? {};
  }
}
